package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClientUtil;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.utils.ThreadLocalUtils;
import org.junit.AfterClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
   private WmNewsMaterialService wmNewsMaterialService;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;
    @Value("${fileServerUrl}")
    private  String fileServerUrl;
    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        }
        //调用工具类上传文件
        try {
            String s = fastDFSClientUtil.uploadFile(multipartFile);
            // 保存到数据库
            WmUser user = ThreadLocalUtils.getUser();
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(s);
            wmMaterial.setUserId(user.getId());
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType(WemediaContans.PIC_TYPE);
            wmMaterial.setIsCollection(WemediaContans.CANCEL_COLLECT_MATERIAL);
            save(wmMaterial);
            return ResponseResult.okResult(fileServerUrl+s);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

    }
    /**
     * 素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 分页查询数据
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());


        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<>();
        if (dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        // 获取登录用户id
        WmUser user = ThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());
        IPage<WmMaterial> result = page(page,wrapper);
        // 给文件添加前缀
        List<WmMaterial> list = result.getRecords();
        list.forEach(item->{
            item.setUrl(fileServerUrl+item.getUrl());
        });
        ResponseResult r = new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        r.setData(list);
        return r;
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询改图片是否被引用
        List<WmNewsMaterial> list = wmNewsMaterialService.list(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (list==null||list.size()==0){
            //可以删除
            //查询文件名
            WmMaterial wmMaterial = getById(id);
            if (wmMaterial!=null){
                //从数据库删除
                removeById(id);
                // 从fsatdfs中删除
                try {
                    fastDFSClientUtil.delFile(wmMaterial.getUrl());
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //被使用,不能删除
            return ResponseResult.errorResult(666,"图片被用了");

        }

    }

    /**
     * 收藏/取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectionMaterial(Integer id,Short isCollection) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial byId = getById(id);
        byId.setIsCollection(isCollection);
        updateById(byId);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
